package com.crazymakercircle.imServer.processer;

import com.crazymakercircle.im.common.bean.msg.ProtoMsg;
import com.crazymakercircle.imServer.server.ServerSession;
import com.crazymakercircle.imServer.server.SessionMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Slf4j
@Service("ChatRedirectProcessor")
public class ChatRedirectProcessor extends AbstractServerProcessor {
    @Override
    public ProtoMsg.HeadType type() {
        return ProtoMsg.HeadType.MESSAGE_REQUEST;
    }

    @Override
    public boolean action(ServerSession fromSession, ProtoMsg.Message proto) {
        // 聊天处理
        ProtoMsg.MessageRequest msg = proto.getMessageRequest();
        log.info("chatMsg | from:{} , to:{}, content:{}", msg.getFrom(), msg.getTo(), msg.getContent());
        // 获取接收方的chatID
        String to = msg.getTo();
        // int platform = msg.getPlatform();
        List<ServerSession> toSessions = SessionMap.inst().getSessionsBy(to);
        if (ObjectUtils.isEmpty(toSessions)) {
            //接收方离线
            log.info("[{}] 不在线，发送失败!", to);
            return false;
        } else {
            toSessions.forEach((session) -> {
                session.writeAndFlush(proto); // 将IM消息发送到接收方
            });
            return true;
        }
    }
}
